package com.example.demo.thread;

import java.util.concurrent.*;

/**
 * 实现Runnable接口方式实现多线程
 *
 * Runnable的run()方法的执行结果是void 因此 及时运行了ExecutorService#Future<?> submit(Runnable task);
 * 返回结果依然是null。需要传入 有返回参数的 Callable 实例
 *
 * @author luowj12
 * @since 2021/4/2 14:25
 */
public class RunnableTest implements Runnable{
    private int ticket =10;
    @Override
    public void run(){
        for(int i=0;i<20;i++){
            if(this .ticket >0){
                System. out.println(Thread.currentThread().getName()+ " 卖票：ticket" +this.ticket--);
            }
        }
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        RunnableTest myThread = new RunnableTest();
        Thread thread1 = new Thread(myThread);
        Thread thread2 = new Thread(myThread);
        thread1.start();
        thread2.start();

        ExecutorService executor = Executors.newCachedThreadPool();

        Future result1 = executor.submit(new Runnable() {
            @Override
            public void run()   {
                int sum = 0;
                for (int i = 0; i < 10; i++) {

                    sum += i;
                }
            }

        });

        System.out.println(result1.get());
    }

}
